package cn.tedu.jdbc;

import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ResourceBundle;

public class JDBCTest06 {
    public static void main(String[] args) {
        ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
        String driver = bundle.getString("driver");
        String url = bundle.getString("url");
        String  user = bundle.getString("user");
        String password = bundle.getString("password");

        Connection conn = null;
        Statement  stmt = null;
        ResultSet rs = null;


        try {
            //1.注册驱动
            Class.forName(driver);
            //2.获取连接
            conn = DriverManager.getConnection(url, user, password);
            System.out.println("connection=" + conn);
            //3.获取数据库操作对象
            stmt = conn.createStatement();
            System.out.println("statement=" + stmt);
            //4.执行sql语句
            String sql = "select id,name,price,create_time from t_product";
            rs = stmt.executeQuery(sql);
            //5.处理查询结果集
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
            while (rs.next()){
                //以特定类型获取数据
                long id = rs.getInt("id");
                String name = rs.getString("name");
                double price =rs.getDouble("price");
                //注意 ：从mysql数据库当中获取的日期类型的数据对应的java类型是java.sql.Date。不是java.util.Date
                Date createTime = rs.getDate("create_time");
                System.out.println(id + "," + name + "," + price + "," + createTime);
                //将java.sql.Date 转换为java.util.Date（通过构造方法来完成转换。）
                java.util.Date date = new java.util.Date(createTime.getTime());
                //进行格式化显示
                String strDate = simpleDateFormat.format(date);
                System.out.println(strDate);

            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            if (conn != null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (stmt != null){
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }



        //6.释放资源
    }
}
